package com.hxjb.config;

import com.hxjb.common.CodeMsg;
import com.hxjb.common.CommonJsonResult;
import com.hxjb.common.ProcessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by wt on 2017/11/20.
 */
@ControllerAdvice
public class ExceptionHandle {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonJsonResult handle(Exception e) {
        e.printStackTrace();
        if(e instanceof ProcessException) {
            ProcessException ex = (ProcessException)e;
            return CommonJsonResult.error(ex.getCm());
        }else if(e instanceof BindException) {
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return CommonJsonResult.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else {
            return CommonJsonResult.error(CodeMsg.SERVER_ERROR);
        }
    }
}
